package com.example.administrator.ygddriver.into.login.driverjoin.weight.weightmessage;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.example.administrator.ygddriver.R;
import com.example.administrator.ygddriver.base.BaseActivity;
import com.example.administrator.ygddriver.base.BaseHint;
import com.example.administrator.ygddriver.base.UserBean;
import com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage.DriverAuthenticationRequestBean;
import com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage.SmallMessageActivity;
import com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage.audit.AuditActivity;
import com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage.credentials.CredentialsActivity;
import com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage.credentials.FileRrequestBean;
import com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage.credentials.PhotoBean;
import com.example.administrator.ygddriver.liteorm.LiteOrmTools;
import com.example.administrator.ygddriver.tool.CustomDatePicker;
import com.example.administrator.ygddriver.tool.GlideImageLoader;
import com.example.administrator.ygddriver.tool.OkGoRequests;
import com.example.administrator.ygddriver.tool.SimpleToolbar;
import com.example.administrator.ygddriver.tool.UrlValuse;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.view.CropImageView;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

public class WeightMessageActivity extends BaseActivity implements View.OnClickListener {
    private SimpleToolbar simpleToolbar;
    private TextView mCityTv, mLzTv, mDjTv, mZcTv, mNextTv;
    private EditText mNameEt, mNumEt, mCarNumEt, mCarNameEt;
    private LinearLayout mPhotoLl;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private String city, province;
    private String date, time;
    private CustomDatePicker mStartPicker, mModelPicker;
    private List<String> addDj;
    private String id, token, c_drivertype;
    private PhotoBean mPhotoBean;
    private TextView mPhotoTv;
    private int REQUEST_CODE_SELECT = 12312;
    private ImagePicker imagePicker;
    private String mPhotoBase64;
    private String timeTag;


    @Override
    public int initLayout() {
        return R.layout.activity_weight_message;
    }

    @Override
    public void initView() {
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        setLocationClientOption();
        mLocationClient.start();
        simpleToolbar = findViewById(R.id.activity_weight_message_stb);
        mCityTv = findViewById(R.id.activity_weight_message_city_tv);
        mPhotoLl = findViewById(R.id.activity_weight_message_photo_ll);
        mNameEt = findViewById(R.id.activity_weight_message_name_et);
        mNumEt = findViewById(R.id.activity_weight_message_num_et);
        mLzTv = findViewById(R.id.activity_weight_message_lz_time_tv);
        mDjTv = findViewById(R.id.activity_weight_message_dj_tv);
        mCarNumEt = findViewById(R.id.activity_weight_message_car_num_et);
        mCarNameEt = findViewById(R.id.activity_weight_message_car_name_et);
        mZcTv = findViewById(R.id.activity_weight_message_zc_time_tv);
        mNextTv = findViewById(R.id.activity_weight_message_next_tv);
        mPhotoTv = findViewById(R.id.activity_weight_message_photo_tv);

        mCityTv.setOnClickListener(this);
        mPhotoLl.setOnClickListener(this);
        mLzTv.setOnClickListener(this);
        mDjTv.setOnClickListener(this);
        mNextTv.setOnClickListener(this);
        mZcTv.setOnClickListener(this);
        mPhotoBean = new PhotoBean();
    }

    @Override
    public void initDate() {
        imagePicker = ImagePicker.getInstance();
        c_drivertype = getIntent().getStringExtra("c_drivertype");
        LiteOrmTools.getInformation(UserBean.class, this, new LiteOrmTools.On<UserBean>() {
            @Override
            public void hasData(UserBean data) {
                id = data.getC_id();
                token = data.getC_token();
            }
        }, new LiteOrmTools.OFF() {
            @Override
            public void noData() {

            }
        });


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ", Locale.CHINA);
        time = sdf.format(new Date());
        date = time.split(" ")[0];
        setSimpleToolbar();
        setCuDatePicker();
    }

    private void setSimpleToolbar() {
        simpleToolbar.setMainTitle("车主信息");
        simpleToolbar.setMainTitleColor("#000000");
        simpleToolbar.setBackIv(R.mipmap.left_title);
        simpleToolbar.setToolColor("#ffffff");
        simpleToolbar.setBackIvClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x002 && resultCode == 0x001) {
            Bundle bundle = data.getExtras();
            mPhotoBean = bundle.getParcelable("result");
            mPhotoTv.setText("上传完成");
        }
//        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
//            if (data != null && requestCode == REQUEST_CODE_SELECT) {
//                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
//                imagePicker.getImageLoader().displayImage(this, images.get(0).path, mHeadIv, mHeadIv.getWidth(), mHeadIv.getHeight());
//                mPhotoBase64 = bitmapToBase64(comp(BitmapFactory.decodeFile(images.get(0).path)));
//                mPhoneMp = comp(BitmapFactory.decodeFile(images.get(0).path));
//                initFileHtml(mPhotoBase64, "3", token);
//            } else {
//                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
//            }
//        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_weight_message_city_tv:
                setCity();
                break;
            case R.id.activity_weight_message_photo_ll:
                Intent intent2 = new Intent(this, CredentialsActivity.class);
                intent2.putExtra("tag", "2");
                startActivityForResult(intent2, 0x002);
                break;
            case R.id.activity_weight_message_lz_time_tv:
                timeTag = "1";
                mStartPicker.show(date);
                break;
            case R.id.activity_weight_message_dj_tv:
                addDj = new ArrayList<>();
                addDj.add("A1");
                addDj.add("A2");
                addDj.add("A3");
                addDj.add("B1");
                addDj.add("B2");
                addDj.add("C1");
                addDj.add("C2");
                addDj.add("C3");
                addDj.add("C4");
                addDj.add("C5");
                addDj.add("D");
                addDj.add("E");
                addDj.add("F");
                addDj.add("M");
                addDj.add("N");
                addDj.add("P");
                mModelPicker = new CustomDatePicker(addDj, this, "选择等级", 1, false, new CustomDatePicker.ResultHandler() {
                    @Override
                    public void handle(String time) {
                        if (time == null) {
                            mDjTv.setText(addDj.get(0));
                        } else {
                            mDjTv.setText(time);
                        }
                    }
                });
                break;
            case R.id.activity_weight_message_next_tv:
                initDriverAuthenticationHtml(id, String.valueOf(mNameEt.getText()), String.valueOf(mNumEt.getText()), String.valueOf(mCityTv.getText())
                        , mPhotoBean.getC_frontface(), mPhotoBean.getC_reverseside(), mPhotoBean.getC_onecarphoto(), mPhotoBean.getC_handheld(), null, c_drivertype, token
                        , String.valueOf(mLzTv.getText()), String.valueOf(mDjTv.getText()), String.valueOf(mCarNumEt.getText()), null
                        , String.valueOf(mCarNameEt.getText()), String.valueOf(mZcTv.getText()), mPhotoBean.getC_driverlicense(), mPhotoBean.getC_vehiclelicense());

                break;
            case R.id.activity_weight_message_zc_time_tv:
                mStartPicker.show(date);
                timeTag = "2";
                break;
        }
    }

    private void setIgPicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
//        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(1);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.CIRCLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(200);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(200);                         //保存文件的高度。单位像素
    }

    //司机端用户认证
    private void initDriverAuthenticationHtml(String c_id, String c_name, String c_idnumber, String c_city, String c_frontface, String c_reverseside, String c_onecarphoto
            , String c_handheld, String c_headportrait, String c_drivertype, String c_token, String c_drivingdate, String c_drivinggrade
            , String c_licensenumber, String c_models, String c_vehicleowner, String c_vehicledate, String c_driverlicense, String c_vehiclelicense) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_token", c_token);
        hashMap.put("c_id", c_id);
        hashMap.put("c_name", c_name);
        hashMap.put("c_idnumber", c_idnumber);
        hashMap.put("c_city", c_city);
        hashMap.put("c_drivinggrade", c_drivinggrade);
        hashMap.put("c_frontface", c_frontface);
        hashMap.put("c_reverseside", c_reverseside);
        hashMap.put("c_onecarphoto", c_onecarphoto);
        hashMap.put("c_handheld", c_handheld);
        hashMap.put("c_headportrait", c_headportrait);
        hashMap.put("c_drivertype", c_drivertype);
        hashMap.put("c_type", "2");
        hashMap.put("c_drivingdate", c_drivingdate);
        hashMap.put("c_licensenumber", c_licensenumber);
        hashMap.put("c_models", c_models);
        hashMap.put("c_vehicleowner", c_vehicleowner);
        hashMap.put("c_vehicledate", c_vehicledate);
        hashMap.put("c_driverlicense", c_driverlicense);
        hashMap.put("c_vehiclelicense", c_vehiclelicense);
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_DRIVER + UrlValuse.DRIVER_AUTHENTICATION, hashMap, DriverAuthenticationRequestBean.class, new OkGoRequests.OnTrue<DriverAuthenticationRequestBean>() {
            @Override
            public void hasData(DriverAuthenticationRequestBean date) {
                if (date.isSuccess()) {
                    Intent intent = new Intent(WeightMessageActivity.this, AuditActivity.class);
                    intent.putExtra("status", date.getResult().getC_status());
                    startActivity(intent);
                    finish();
                }
            }
        }, new OkGoRequests.OnError<DriverAuthenticationRequestBean>() {
            @Override
            public void noData() {

            }
        });

    }


    private void setCuDatePicker() {
        mStartPicker = new CustomDatePicker(this, "请选择时间", new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                if (timeTag.equals("1")) {
                    mLzTv.setText(time.split(" ")[0]);
                } else {
                    mZcTv.setText(time.split(" ")[0]);
                }

            }
        }, "1950-01-01 00:00", "2027-12-31 23:59");//"2027-12-31 23:59"
        mStartPicker.showSpecificTime(false, 0);
        mStartPicker.setIsLoop(false);
    }


    private void setCity() {
        CityPicker.getInstance().setFragmentManager(getSupportFragmentManager())
                .enableAnimation(true)
                .setOnPickListener(new OnPickListener() {
                    @Override
                    public void onPick(int position, City data) {
                        if (data != null) {
                            mCityTv.setText(data.getName());

                        }
                    }

                    @Override
                    public void onLocate() {
                        mLocationClient.start();
                    }
                }).show();
        mLocationClient.start();
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            city = location.getCity();
            String[] cityy = new String[0];
            if (!TextUtils.isEmpty(city)) {
                cityy = city.split("市");
            }

            province = location.getProvince();
            float radius = location.getRadius();    //获取定位精度，默认值为0.0f
            int errorCode = location.getLocType();
            Log.d("111111", "errorCode:" + errorCode);
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
            String addr = location.getAddrStr();
            mLocationClient.stop();
            if (errorCode == 161 || errorCode == 61) {
                CityPicker.getInstance()
                        .locateComplete(new LocatedCity(cityy[0], province, null), LocateState.SUCCESS);
            }

        }
    }

    private void setLocationClientOption() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setOpenGps(true);
        option.setLocationNotify(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setEnableSimulateGps(false);
        mLocationClient.setLocOption(option);
        option.setIsNeedAddress(true);
        option.setIsNeedLocationPoiList(true);

    }

    //上传图片
    private void initFileHtml(String fileBase64Str, String type, String c_token) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("fileBase64Str", fileBase64Str);
        hashMap.put("type", type);
        hashMap.put("c_token", c_token);
        hashMap.put("c_type", "2");
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_UPLOAD + UrlValuse.FILE, hashMap, FileRrequestBean.class, new OkGoRequests.OnTrue<FileRrequestBean>() {
            @Override
            public void hasData(FileRrequestBean date) {
                if (date.isSuccess()) {
//                    mHeadPlace = date.getResult().getDbPath();
//                    savePhotoToSD(mPhoneMp, mAccount + "HEAD_PHOTO");
                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(WeightMessageActivity.this, "提示", date.getLocalizedMessage());
                    baseHint.show();
                }
            }
        }, new OkGoRequests.OnError<FileRrequestBean>() {
            @Override
            public void noData() {

            }
        });
    }

    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private Bitmap comp(Bitmap image) {
        float scale = 768f / (float) image.getWidth();
        return compressImage(Bitmap.createScaledBitmap(image, 768,
                (int) (image.getHeight() * scale), false));
    }

    private Bitmap compressImage(Bitmap image) {

        Bitmap bitmap = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 40) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(
                baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片

        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            isBm.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 保存照片到SD卡的指定位置
     */
    private void savePhotoToSD(Bitmap bitmap, String name) {
        File outputImage = new File(Environment.getExternalStorageDirectory(), "/YGDDriver/Photo/" + name + ".jpg");
        if (!outputImage.getParentFile().exists()) {
            outputImage.getParentFile().mkdirs();
        }
        try {
            FileOutputStream fos = new FileOutputStream(outputImage);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
